﻿#region  文件信息

// ---------------------------------------------------------------------------------------
// <copyright file="AliCore.cs" company="">
// 作者：李帅伦
// </copyright>
// <summary>
// 类型简介：
// 类型详细：AliCore.cs
// 创建时间：2015-01-07 18:30
// 修改时间：2014-12-25 16:02
// </summary>
// ---------------------------------------------------------------------------------------
#endregion

namespace Payment.Albaba.Com
{
    #region

    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Linq;
    using System.Text;
    using System.Web;

    using WebCommon;

    #endregion

    /// <summary>
    ///     The ali core.
    /// </summary>
    internal class AliCore
    {
        #region Public Methods and Operators

        /// <summary>
        /// 建立请求，以表单HTML形式构造（默认）
        /// </summary>
        /// <param name="sParaTemp">
        /// </param>
        /// <param name="gateway">
        /// 网关.
        /// </param>
        /// <param name="inputCharset">
        /// 编码.
        /// </param>
        /// <returns>
        /// 提交表单HTML文本
        /// </returns>
        public static string BuildRequest(Dictionary<string, string> sParaTemp, string gateway, string inputCharset)
        {
            sParaTemp = sParaTemp.OrderBy(x => x.Key).ToDictionary(a => a.Key, b => b.Value);

            // 待请求参数数组
            var sbHtml = new StringBuilder();

            sbHtml.Append(
                "<form id='alipaysubmit' name='alipaysubmit' action='" + gateway + "_input_charset="
                + inputCharset + "' method='" + "get" + "'>");

            foreach (var temp in sParaTemp)
            {
                sbHtml.Append("<input type='hidden' name='" + temp.Key + "' value='" + temp.Value + "'/>");
            }

            // submit按钮控件请不要含有name属性
            sbHtml.Append("<input type='submit' value='确认' style='display:none;'></form>");

            sbHtml.Append("<script>document.forms['alipaysubmit'].submit();</script>");

            return sbHtml.ToString();
        }

        /// <summary>
        /// The create link string urlencode.
        /// </summary>
        /// <param name="dicArray">
        /// The dic array.
        /// </param>
        /// <param name="code">
        /// The code.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string CreateLinkStringUrlencode(Dictionary<string, string> dicArray, Encoding code)
        {
            StringBuilder prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value, code) + "&");
            }

            // 去掉最後一個&字符
            int nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        /// <summary>
        /// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <param name="httpRequest">
        /// The http Request.
        /// </param>
        /// <returns>
        /// request回来的信息组成的数组
        /// </returns>
        public static Dictionary<string, string> GetRequestPost(HttpRequestBase httpRequest)
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            NameValueCollection coll = httpRequest.Form;

            // Get names of all forms into a string array.
            string[] requestItem = coll.AllKeys;

            for (var i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], coll[requestItem[i]]);
            }

            return sArray;
        }

        /// <summary>
        /// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <param name="httpRequest">
        /// The http Request.
        /// </param>
        /// <returns>
        /// request回来的信息组成的数组
        /// </returns>
        public static Dictionary<string, string> GetRequestGet(NameValueCollection coll)
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();
             
            // Get names of all forms into a string array.
            string[] requestItem = coll.AllKeys;

            for (var i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], coll[requestItem[i]]);
            }

            return sArray;
        }
        /// <summary>
        /// The verify.
        /// </summary>
        /// <param name="preSignStr">
        /// The pre sign str.
        /// </param>
        /// <param name="sign">
        /// The sign.
        /// </param>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="inputCharset">
        /// The input charset.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool Verify(string preSignStr, string sign, string key, string inputCharset)
        {
            return true;
        }

        #endregion

        #region Methods

        /// <summary>
        /// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        /// </summary>
        /// <param name="dictionary">
        /// The dictionary.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        internal static string CreateLinkString(Dictionary<string, string> dictionary)
        {
            StringBuilder prestr = new StringBuilder();
            foreach (var temp in dictionary)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            // 去掉最後一個&字符
            int nLen = prestr.Length;
            if (nLen > 0)
            {
                prestr.Remove(nLen - 1, 1);
            }

            return prestr.ToString();
        }

        /// <summary>
        /// 除去数组中的空值和签名参数并以字母a到z的顺序排序
        /// </summary>
        /// <param name="dictionary">
        /// The dictionary.
        /// </param>
        /// <returns>
        /// 过滤后的参数组
        /// </returns>
        internal static Dictionary<string, string> FilterPara(Dictionary<string, string> dictionary)
        {
            Dictionary<string, string> dicArray = new Dictionary<string, string>();
            foreach (var temp in dictionary)
            {
                if (temp.Key.ToLower() != "sign" && temp.Key.ToLower() != "sign_type"
                    && !string.IsNullOrEmpty(temp.Value))
                {
                    dicArray.Add(temp.Key, temp.Value);
                }
            }

            return dicArray.OrderBy(x => x.Key).ToDictionary(a => a.Key, b => b.Value);
        }

        /// <summary>
        /// 签名字符串
        /// </summary>
        /// <param name="prestr">
        /// 需要签名的字符串
        /// </param>
        /// <param name="key">
        /// 密钥
        /// </param>
        /// <returns>
        /// 签名结果
        /// </returns>
        internal static string Md5Sign(string prestr, string key)
        {
            prestr = prestr + key;
            return Encryption.Md532(prestr);
        }

        #endregion
    }
}